<?php 
require_once dirname(__FILE__). '/../libraries/Google/Client.php';
require_once dirname(__FILE__). '/../libraries/Google/Service/Content.php';

abstract class Google_API_Shopping {
    protected $merchant_id;
    protected $service;

    const CONFIG_FILE_NAME = 'config.json';

    public function __construct () {
        $config_file = dirname(__FILE__) . '/' . self::CONFIG_FILE_NAME;
        
        $client = new Google_Client();
        $client->setApplicationName('mkt');
        $client->setClientId('631122200630-uc2c8hf8n2thkdb6l4rm3advbi84cb00.apps.googleusercontent.com');
        $client->setClientSecret('vURIJz753D9ZnDz113vGuV4F');
        $client->setRedirectUri('http://vblog-it.com/wp-admin/');
        $client->setScopes('https://www.googleapis.com/auth/content');
       
        if (isset($_SESSION['oauth_access_token'])) {
            $client->setAccessToken($_SESSION['oauth_access_token']);
        } elseif (isset($_GET['code'])) {
            
            $token = $client->authenticate($_GET['code']);
            $_SESSION['oauth_access_token'] = $token;
            
            echo $token;
            
        } else {
            header('Location: ' . $client->createAuthUrl());
            exit;
        }
//        if (file_exists($config_file)) {
//            $config = json_decode(file_get_contents($config_file));
//        }
//
//        if (!$config) {
//          throw new Exception(sprintf('Could not find or read the config file at '
//              . '%s. You can use the config.json file in the samples root as a '
//              . 'template.', $config_file));
//        }
//       
//        $client = new Google_Client();
//        $client->setApplicationName($config->applicationName);
//        $client->setClientId($config->clientId);
//        $client->setClientSecret($config->clientSecret);
//        
//        try {
//            $client->refreshToken($config->refreshToken);
//        } catch (Google_Auth_Exception $exception) {
//            print (str_repeat('*', 40));
//            print ("Your refresh token was missing or invalid, fetching a new one\n");
//            $refresh_token = $this->getRefreshToken($client);
//            $config->refreshToken = $refresh_token;
//            file_put_contents($config_file, json_encode($config));
//            print ("Refresh token saved to your config file\n");
//            print (str_repeat('*', 40));
//        }

        $this->merchant_id = 100828451;
        $this->service = new Google_Service_Content($client);
    }

    abstract public function run();

    private function getRefreshToken (Google_Client $client) {
        $client->setRedirectUri('http://test14.elinext.com/wp-admin?gapi=1');
        $client->setScopes('https://www.googleapis.com/auth/content');
        $client->setAccessType('offline'); // So that we get a refresh token

        printf("Visit the following URL and log in:\n\n\t%s\n\n",
        $client->createAuthUrl());
        print ('Then type the resulting code here: ');
        defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
        $code = trim(fgets(STDIN));
        
        $client->authenticate($code);

        $token = $client->getAccessToken();
        $decoded_token = json_decode($token);

        return $decoded_token->refresh_token;
    }

    // Retry a function with back off
    protected function retry($function, $parameter, $max_attempts = 5) {
        $attempts = 1;

        while ($attempts <= $max_attempts) {
            try {
              return call_user_func(array($this, $function), $parameter);
            } catch (Google_Service_Exception $exception) {
              sleep($attempts * $attempts);
              $attempts++;
            }
        }
    }
}

class Products_Google_API_Shopping extends Google_API_Shopping {
    // These constants define the identifiers for all of our example products
    // The products will be sold online
    const CHANNEL = 'online';
    // The product details are provided in English
    const CONTENT_LANGUAGE = 'en';
    // The products are sold in the United States
    const TARGET_COUNTRY = 'US';

    // This constant defines how many example products to create in a batch
    const BATCH_SIZE = 10;

    public function run() {
        $example_product_id = 'book123456';
        $example_product = $this->createExampleProduct($example_product_id);

        $this->insertProduct($example_product);
    }
    
    public function insertProduct(Google_Service_Content_Product $product) {
        
        $response = $this->service->products->insert($this->merchant_id, $product);
        
        // Our example product generator does not set a product_type, so we should
        // get at least one warning.
        $warnings = $response->getWarnings();
        print ('Product created, there are ' . count($warnings) . " warnings\n");
        foreach($warnings as $warning) {
            printf(" [%s] %s\n", $warning->getReason(), $warning->getMessage());
        }
    }
    
    private function createExampleProduct($offer_id) {
        $product = new Google_Service_Content_Product();

        $product->setOfferId($offer_id);
        $product->setTitle('A Tale of Two Cities');
        $product->setDescription('A classic novel about the French Revolution');
        $product->setLink('http://vblog-it.com');
        $product->setImageLink('http://my-book-shop.com/tale-of-two-cities.jpg');
        $product->setContentLanguage(self::CONTENT_LANGUAGE);
        $product->setTargetCountry(self::TARGET_COUNTRY);
        $product->setChannel(self::CHANNEL);
        $product->setAvailability('in stock');
        $product->setCondition('new');
        $product->setGoogleProductCategory('Media > Books');
        $product->setGtin('9780007350896');

        $price = new Google_Service_Content_Price();
        $price->setValue('2.50');
        $price->setCurrency('USD');

        $product->setPrice($price);

        $shipping_price = new Google_Service_Content_Price();
        $shipping_price->setValue('0.99');
        $shipping_price->setCurrency('USD');

        $shipping = new Google_Service_Content_ProductShipping();
        $shipping->setPrice($shipping_price);
        $shipping->setCountry('US');
        $shipping->setService('Standard shipping');

        $product->setShipping(array($shipping));

        $shipping_weight = new Google_Service_Content_ProductShippingWeight();
        $shipping_weight->setValue(200);
        $shipping_weight->setUnit('grams');

        $product->setShippingWeight($shipping_weight);

        return $product;
    }
}

$product_google_api_shopping = new Products_Google_API_Shopping();
$product_google_api_shopping->run();